package com.itcncp.ucenter.rpc.service.impl;

import com.itcncp.common.annotation.BaseService;
import com.itcncp.common.base.BaseServiceImpl;
import com.itcncp.common.model.OrderCodeType;
import com.itcncp.common.pingplusplus.PingppUtil;
import com.itcncp.common.pingplusplus.model.Transfer;
import com.itcncp.common.util.OrderUtils;
import com.itcncp.ucenter.dao.mapper.UserAccountInfoMapper;
import com.itcncp.ucenter.dao.mapper.UserCashinOpJnlMapper;
import com.itcncp.ucenter.dao.model.UserAccountInfo;
import com.itcncp.ucenter.dao.model.UserAccountInfoExample;
import com.itcncp.ucenter.dao.model.UserCashinOpJnl;
import com.itcncp.ucenter.rpc.api.UserAccountInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
* UserAccountInfoService实现
* Created by itcncp on 2018/1/12.
*/
@Service
@Transactional
@BaseService
public class UserAccountInfoServiceImpl extends BaseServiceImpl<UserAccountInfoMapper, UserAccountInfo, UserAccountInfoExample>
        implements UserAccountInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserAccountInfoServiceImpl.class);

    @Autowired
    UserAccountInfoMapper userAccountInfoDao;

    @Autowired
    UserCashinOpJnlMapper userCashinOpJnlDao;


    /**
     * 更新提现状态
     * @param orderno
     * @param type 1失败 3成功
     * @return 1失败 2成功
     */
    @Override
    public Integer cashinOpJnlState(String orderno, Integer type) {

        //查询订单是否存在
        UserCashinOpJnl userCashinOpJnl = userCashinOpJnlDao.selectByPrimaryKey(orderno);

        if(null != userCashinOpJnl){

            if(userCashinOpJnl.getCashinState()==3){
                //提现订单是否已经扣款成功
                return 2;
            }

            //更新提现状态
            userCashinOpJnl.setCashinState(type.byteValue());

            if(type == 3){
                //提现成功

                String message = "恭喜您提现成功，余额到您提现银行卡账户中";

                userCashinOpJnl.setRemark(message);

                userCashinOpJnlDao.updateByPrimaryKeySelective(userCashinOpJnl);

                //提现成功短信告知，并将提现备注修改

                return 2;
            }

            //更新用户信息账户信息
            UserAccountInfo userAccountInfo =
                    userAccountInfoDao.selectByPrimaryKey(userCashinOpJnl.getUserId());

            if(null != userAccountInfo){

                //提现失败将金额返回给用户
                BigDecimal amount = userAccountInfo.getAccountBalance().add(userCashinOpJnl.getCashinAmount());

                userAccountInfoDao.updateByPrimaryKeySelective(userAccountInfo);

                String message = "提现失败，资金将返回到余额中，您可尝试再次发起余额提现";

                userCashinOpJnl.setRemark(message);

                userCashinOpJnlDao.updateByPrimaryKeySelective(userCashinOpJnl);

                //提现失败短信告知，并将提现备注修改


                return  2;
            }

        }
        return  1;

    }


    /**
     * 用户提现
     * @param userId
     * @param amount 提现金额
     * @param bankcardNo  卡号
     * @param bankId   银行编号
     * @param authName 姓名
     * @param bankcardType 银行卡种类
     * @return
     */
    @Override
    public UserAccountInfo withdrawals(Long userId,  BigDecimal amount, String bankcardNo, String bankId,
                                       String authName, Integer bankcardType) {


        //生成提现订单号
        Long orderNo = OrderUtils.createOrderId(OrderCodeType.CASHIN_NO);
        //为 20 ~ 40 位不能重复的数字字母组合，
        // 必须以签约的通联的商户号开头（建议组合格式：
        // 通联商户号 + 时间戳 + 固定位数顺序流水号，不包含+号）
        String allinpayNo = "20058600000154101"+orderNo.toString();

        //查询用户账户余额
        UserAccountInfo userAccountInfo = userAccountInfoDao.selectByPrimaryKey(userId);

        if(null == userAccountInfo){
            return null;
        }

        //账户资金不足，则提现失败
        if(userAccountInfo.getAccountBalance().doubleValue() < amount.doubleValue()){
            return null;
        }

        //更新用户资金
        //变动钱金额
        BigDecimal oldBalance = userAccountInfo.getAccountBalance();
        //提现后金额
        BigDecimal nowBalance = userAccountInfo.getAccountBalance().subtract(amount);
        userAccountInfo.setAccountBalance(nowBalance);

        //手续费
        BigDecimal feeAmount = new BigDecimal("200");
        //实际到账金额
        BigDecimal actAmount = amount.subtract(feeAmount);

        String cardNumber = bankcardNo;
        String userName = authName;
        String openBankCode = bankId;
        Integer cardType = bankcardType;
        String description = "正在提现中，预计两个工作日到账！";

        Transfer transfer = PingppUtil.pingTransferAllinpay(actAmount.toString(),allinpayNo
                ,bankcardNo,authName,bankId,bankcardType,description);

        if(null == transfer){
            return null;
        }

        UserCashinOpJnl cashinOpJnl = new UserCashinOpJnl();
        cashinOpJnl.setCashinNo(allinpayNo);
        cashinOpJnl.setUserId(userId);
        cashinOpJnl.setCashinAmount(amount);
        cashinOpJnl.setCashinFee(feeAmount);
        cashinOpJnl.setCashinActAmount(actAmount);
        cashinOpJnl.setCashinCardno(bankcardNo);
        cashinOpJnl.setCashinTime(new Date());
        cashinOpJnl.setCashinState(new Byte("2"));
        cashinOpJnl.setTransferId(transfer.getId());
        cashinOpJnl.setChannel(new Byte("5"));
        cashinOpJnl.setOldBalance(oldBalance);
        cashinOpJnl.setNowBalance(nowBalance);
        cashinOpJnl.setRemark(description);

        //添加提现记录
        userCashinOpJnlDao.insertSelective(cashinOpJnl);

        //更新账户资金
        userAccountInfoDao.updateByPrimaryKeySelective(userAccountInfo);

        return  userAccountInfo;
    }

}